package com.xuan.webfinally.service.impl;

import com.xuan.webfinally.entity.SysUser;
import com.xuan.webfinally.mapper.SysUserMapper;
import com.xuan.webfinally.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.webfinally.utils.JwtTool;
import com.xuan.webfinally.utils.Result;
import com.xuan.webfinally.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author gyuxuan
 * @since 2025-05-18
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private final JwtTool jwtTool;
    private final SysUserMapper sysUserMapper;
//    private final PasswordEncoder passwordEncoder;
//    private final SecurityUtils  securityUtils;
    @Override
    public Result<List<Map<String,String>>> login(String username, String password) {
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            return Result.error("用户名或密码不能为空");
        }
//        SysUser user = getOne(lambdaQuery().eq(SysUser::getUserName, username));
        SysUser user = sysUserMapper.selectOne(username);
        if (user == null || !SecurityUtils.matchesPassword(password, user.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        // 生成Token
        String token = jwtTool.createToken(user.getUserId(), Duration.ofHours(1));

        List<Map<String,String>> maps = new ArrayList<>();
        maps.add(Map.of("token", token));
        maps.add(Map.of("username", username));
        return Result.success(maps);
    }

}
